package com.heima.behavior.service.impl;

import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 行为记录业务实现
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public synchronized ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        log.info(" 参数: userId = {}, 设备id = {}",userId,equipmentId);
        //1. 判断userId是否为空
        if (userId != null) {
            //不为空 使用userId查询 行为实体 (refId = 用户id     type = 用户类型  )
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            ApBehaviorEntry apBehaviorEntry1 = new ApBehaviorEntry();
            if (apBehaviorEntry == null) {
                //如果不存在基于userId创建实体数据
                apBehaviorEntry1.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry1.setRefId(userId);
                mongoTemplate.insert(apBehaviorEntry1);
            }
            //返回行为实体
            return apBehaviorEntry1;
        }
        //2. 判断设备id是否为空
        if (equipmentId != null) {
            //不为空 使用设备id查询  行为实体 (refId = 设备id   type = 设备类型)
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
            if (behaviorEntry == null) {
                //如果不存在基于设备id创建实体数据
                apBehaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                apBehaviorEntry.setRefId(equipmentId);
                mongoTemplate.insert(apBehaviorEntry);
            }
            //返回行为实体
            return apBehaviorEntry;
        }
        //3. 如果userId和设备id都不存在  返回null 调用者需要判断null
        return null;
    }
}
